import base64
import json

from django.core.exceptions import ValidationError
from django.shortcuts import render,HttpResponse, redirect
from django.views.decorators.csrf import csrf_exempt
from user import models
from datetime import date, datetime
# Create your views here.
import time

from django import forms
from user.utils.encrtpy import md5

from user.utils.code import check_code
from io import BytesIO

import requests, re

class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj)
class UserModelForm(forms.ModelForm):
    class Meta:
        model = models.UserProfile
        fields = ['email', 'password', 'create_time']
        # 生成Inpu框
        # widgets = {
        #     "name": forms.TextInput(attrs={'class': 'form-control'})
        #     "password": forms.PasswordInput(attrs={'class': 'form-control'})
        # }
        # 生成Inpu框
        # def __int__(self, *args, **kwargs):
        #     super.__init__(*args, **kwargs)
        #     for name, field in self.fields.items():
        #         print(name, field)
        #         if name == 'password':
        #             continue
        #         field.widget.attrs = {'class': "form-control",'placeholder': self.label}
    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        # 密码md5加密
        return md5(pwd)

# 用户新增
@csrf_exempt
def user_create(request):
    if request.method == 'POST':
        # form = UserModelForm()
        email = request.POST.get('email')
        isok = models.UserProfile.objects.filter(email=email).first()
        if isok:
            return HttpResponse(
                json.dumps({
                    'code': 403,
                    'msg': '用户已存在',
                }))
        # 数据校验
        # 获取传过来的数据
        form = UserModelForm(data=request.POST)
        # 校验
        if form.is_valid():
            print(form.cleaned_data)
            # 自动保存到数据库
            form.save()
            return HttpResponse(
                json.dumps({
                    'code': 200,
                    'msg': '注册成功',
                }))
        else:
            return HttpResponse(
                json.dumps({
                    'code': 403,
                    'msg': '注册失败',
                }))

# 用户列表
@csrf_exempt
def user_list(request):
    if request.method == 'POST':
        email = request.POST.get('email')
        data_list = models.UserProfile.objects.all()
        init_data = []
        if email:
            for i in data_list:
                if email in i.email:
                    init_data.append({
                        'id': i.id,
                        'email': i.email,
                        'role': i.role,
                        'nike_name': i.nike_name,
                        'create_time': i.create_time,
                    })
        else:
            for i in data_list:
                init_data.append({
                    'id': i.id,
                    'email': i.email,
                    'role': i.role,
                    'nike_name': i.nike_name,
                    'create_time': i.create_time,
                })
        return HttpResponse(json.dumps({
            'code': 200,
            'data': init_data,
            'msg': 'success',
        },cls=ComplexEncoder))
class UseLoginForm(forms.Form):
    email = forms.CharField(
        label='邮箱',
        widget=forms.TextInput(attrs={'class':'form-control'})
    )
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput(attrs={'class':'form-control'})
    )
    code = forms.CharField(
        label='验证码',
        widget=forms.TextInput,
        required=False
    )


    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        return md5(pwd)

# 用户登录
@csrf_exempt
def login(request):
    if request.method == 'POST':
        form = UseLoginForm(data=request.POST)
        if form.is_valid():
            user_input_code = form.cleaned_data.pop('code')
            imgcode = request.session.get('image_code', '')
            if user_input_code and user_input_code.upper() != imgcode.upper():
                return HttpResponse(
                    json.dumps({
                        'code': 403,
                        'msg': '验证码错误',
                    }))
            user_info = models.UserProfile.objects.filter(**form.cleaned_data).first()
            if not user_info:
                return HttpResponse(
                    json.dumps({
                        'code': 403,
                        'msg': '用户名或密码错误',
                    }))
            else:
                # 用户名或密码正确
                # 网站生成随机字符串;写到用户浏览器的cookie，在写入到session中
                request.session['info'] = {'id': user_info.id, 'email': user_info.email}
                # session超时时间为7天
                request.session.set_expiry(60 * 60 * 23 * 7)
                return HttpResponse(
                    json.dumps({
                        'code': 200,
                        'data':{
                           'token': '127.0.0.1'
                        },
                        'msg': '登录成功',
                    }))
        else:
            return HttpResponse(
                json.dumps({
                    'code': 401,
                    'msg': '登录失败',
                }))

class UseEditModelForem(forms.ModelForm):
    class Meta:
        model = models.UserProfile
        fields = ['email', 'password', 'role', 'nike_name', 'birthday', 'gender', 'address', 'image', 'weixin', 'name', 'idcard','qq','nation']

# 用户修改
@csrf_exempt
def user_edit(request):
    if request.method == 'POST':
        user_id = request.POST.get('id')
        row_object = models.UserProfile.objects.filter(id=user_id).first()
        form = UserModelForm(data=request.POST, instance=row_object)
        # 校验
        if form.is_valid():
            form.save()
            return HttpResponse(
                json.dumps({
                    'code': 200,
                    'msg': '修改成功',
                }))
        else:
            return HttpResponse(
                json.dumps({
                    'code': 403,
                    'msg': '修改失败',
                }))


# 用户删除
@csrf_exempt
def user_delete(request):
    if request.method == 'POST':
        user_id = request.POST.get('id')
        models.UserProfile.objects.filter(id=user_id).delete()
        return HttpResponse(
            json.dumps({
                'code': 200,
                'msg': '删除成功',
            }))


# 重置密码

class UseResetModelForm(forms.ModelForm):
    class Meta:
        model = models.UserProfile
        fields = ['password']

    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        md5_pwd = md5(pwd)
        # 检验两次密码是否一致
        exists = models.UserProfile.objects.filter(id=self.instance.pk,password=md5_pwd).exists()
        if exists:
            raise ValidationError('密码重复')
        # 密码md5加密
        return md5(pwd)

@csrf_exempt
def user_reset(request):
    if request.method == 'POST':
        user_id = request.POST.get('id')
        row_object = models.UserProfile.objects.filter(id=user_id).first()
        form = UserModelForm(data=request.POST, instance=row_object)
        # 校验
        if form.is_valid():
            form.save()
            return HttpResponse(
                json.dumps({
                    'code': 200,
                    'msg': '修改成功',
                }))
        else:
            return HttpResponse(
                json.dumps({
                    'code': 403,
                    'msg': '修改失败',
                }))
# 注销登录
def login_out(request):
    request.session.clear()
    return HttpResponse(json.dumps({
                    'code': 200,
                    'msg': '退出登录成功',
                }))

def image_code(request):
    """生成图片验证码"""
    img, code_string = check_code()

    # 写入到session中
    request.session['image_code'] = code_string

    # 验证码超时
    request.session.set_expiry(60)

    stream = BytesIO()
    img.save(stream,'png')
    buf_bytes = stream.getvalue()

    base64_data = base64.b64encode(buf_bytes)
    with open('code.txt', 'wb') as file:
        file.write(b'data:image/png;base64,'+base64_data)
    base64_data2 = 'data:image/png;base64,'+str(base64.b64encode(buf_bytes),'utf-8')
    return HttpResponse(json.dumps(
        {
            'code': 200,
            'data': base64_data2,
            'msg': '生成验证码成功'
        }
    ))

# 接口列表

def interface_list(request):
    if request.method == 'GET':
        list = []
        data_list = models.InterfaceProfile.objects.all()
        print(data_list)
        for obj in data_list:
            list.append({
                'id': obj.id,
                'name': obj.name,
                'address_before': obj.address_before,
                'address_after': obj.address_after,
                'state':obj.state,
                'developer':obj.developer,
            })
        return HttpResponse(json.dumps({
            'code': 200,
            'data': list,
            'msg':'success',
        }))

# 新增接口
@csrf_exempt
def interface_add(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        address_before = request.POST.get('address_before')
        address_after = request.POST.get('address_after')
        state = request.POST.get('state')
        developer = request.POST.get('developer')
        # form = InterfaceModelForm()
        print(name, address_before, address_after, state, developer)
        if name:
            models.InterfaceProfile.objects.create(name=name,address_before=address_before,address_after=address_after,state=state,developer=developer)
            return HttpResponse(json.dumps({
                'code': 200,
                'msg': '新增成功'
            }))
        else:
            return HttpResponse(json.dumps({
                'code': 403,
                'msg': '新增失败'
            }))

# 数据大屏
def open_echarts(request):
    return  render(request, 'echarts.html', {'form': {}})

# 前端连调
def go_open_echarts(request):
    return redirect('/x1/open/echarts')

# 去水印

def tool_watermark(reauest):
    print(reauest)
    # douyin = 'https://v.douyin.com/2AAVEak'
    # # url = reauest.POST.get('url')
    # # 模拟手机请求头
    # headers = {
    #     'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Mobile Safari/537.36 Edg/103.0.1264.62'
    # }
    # print(douyin)
    # ree = requests.get(douyin,headers=headers)
    # print(ree)
    #
    # new_url = ree.url
    #
    # # 提取视频id
    #
    # id = re.search(r'/video/(.*?)/', new_url).group(1)
    # # 提取视频链接地址
    # url = 'https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids=' + id
    # ree = requests.get(url,headers=headers)
    # wm = ree.json()
    # n_wm = wm['item_list'][0]['video']['play_addr']['url_list'][0].replace('wm','')
    # print(n_wm)

    return HttpResponse(1)
